const http = require("http")
const {resolve} = require("path")
const fs=require('fs')


let app = http.createServer((req,res)=>{
  let {pathname}=new URL(req.url,'http://localhost:80')
  // res.setHeader('content-type','text/html;charset=utf-8') 设置请求头会导致所有请求的都是页面响应，导致css和img的请求失效
  console.log(pathname);
  if (pathname === '/'){
    fs.readFile(resolve(__dirname,'./public/index.html'),{
      encoding:'utf-8'
    },(err,data)=>{
      console.log(err);
      let pat=`<a href="/index">进入index</a><br><a href="/admin">进入admin</a>`
      // res.end(pat)
      res.end(data +pat)
    })
   
  }else if(pathname==='/css/app.css'){
    fs.readFile(resolve(__dirname,'./public/css/app.css'),{
      encoding:'utf-8'
    },(err,data)=>{
      // console.log(err);
      
      // res.end(pat)
      res.end(data)
    })
  }
  else if(pathname==='/index'){
    fs.readFile(resolve(__dirname,'./public/index.html'),{
      encoding:'utf-8'
    },(err,data)=>{
      if(err){
        res.end('路径错误')
      }else{
        res.end(data)
      }  
    })
  }else if(pathname==='/img/1-ditu.png'){
    fs.readFile(resolve(__dirname,'./public/img/1-ditu.png'),(err,data)=>{
      if (err) return
      res.end(data)
    })
  }
  else if(pathname==='/admin'){
    fs.readFile(resolve(__dirname,'./public/admin.html'),{
      encoding:'utf-8'
    },(err,data)=>{
      if(err){
        res.end('路径错误')
      }else{
        res.end(data)
      }  
    })
  }
   
})
app.listen(80,()=>{
  console.log('启动了');
})